﻿using System;
using System.Collections.Generic;

namespace Librarinth
{
	public abstract class Module<T> where T : struct
	{
		readonly List<int> AliveIndex	= new List<int>();

		public int Count { get { return AliveIndex.Count; } }
		public T[] Datas { get { return DataPool<T>.Datas; } }
		public IEnumerable<int> AllIndex { get { return AliveIndex; } }

		protected virtual void OnResize(int newSize) { }
		protected abstract void Alloc(ref T data);
		protected abstract void Free(ref T data);

		public void Alloc(out int index)
		{
			DataPool<T>.Alloc(out index);

			if(AliveIndex.Contains(index))
				throw new Exception("Error Duplicate Index");
			AliveIndex.Add(index);

			Alloc(ref DataPool<T>.Datas[index]);
		}
		public void Free(ref int index)
		{
			if(!AliveIndex.Contains(index))
				throw new Exception("Error Remove Wrong Index");
			AliveIndex.Remove(index);

			Free(ref DataPool<T>.Datas[index]);

			DataPool<T>.Free(ref index);
		}
	}
}
